package rlyy.framework.netty.inithandler;

import rlyy.framework.netty.inithandler.strategy.IRequestProcess;
import rlyy.framework.netty.interceptor.MyHandlerInterceptor;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import org.springframework.lang.Nullable;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * 程序处理器和拦截器链
 * @author yuanqinglong
 * @since 2020/12/8 17:30
 */
public class MyHandlerExecutionChain {

    /**
     * 执行业务逻辑的处理器
     */
    private IRequestProcess handler;

    @Nullable
    private final List<MyHandlerInterceptor> interceptorList;


    public MyHandlerExecutionChain(@Nullable List<MyHandlerInterceptor> interceptorList) {
        this.interceptorList = interceptorList;
    }

    public MyHandlerExecutionChain(IRequestProcess handler, @Nullable List<MyHandlerInterceptor> interceptorList) {
        this.handler = handler;
        this.interceptorList = interceptorList;
    }

    public IRequestProcess getHandler() {
        return handler;
    }

    public void setHandler(IRequestProcess handler) {
        this.handler = handler;
    }

    @Nullable
    public List<MyHandlerInterceptor> getInterceptorList() {
        return interceptorList;
    }

    /**
     * 拦截器预处理请求
     * @param request 请求信息
     * @param ctx 返回
     * @return true or false
     * @throws Exception 异常
     */
    boolean applyPreHandle(FullHttpRequest request, ChannelHandlerContext ctx) throws Exception {
        List<MyHandlerInterceptor> interceptors = getInterceptorList();
        if (!ObjectUtils.isEmpty(interceptors)) {
            for (MyHandlerInterceptor interceptor : interceptors) {
                if (!interceptor.preHandle(request, ctx)) {
                    interceptor.afterCompletion(request, ctx);
                    return false;
                }
            }
        }
        return true;
    }
}
